var express = require('express')
var mysql = require('mysql');
var app = express();
app.all('*', function(req, res, next) { // CORS 跨域
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers", "X-Requested-With")
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8")
    next()
})

// 注册端接口
app.get('/register', function(req, res) {
    res.status(200);
    // 获取数据
    var usr = req.query.usr;
    var pwd = req.query.pwd;
    var phone = req.query.phone;
    console.log(req.query);
    // 连接数据库
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'gp12'
    })
    connection.connect();
    // 查询功能
    var sql = `SELECT * FROM ymatou WHERE userName='${usr}'`;
    connection.query(sql, function(error, results, fields) {
        if (results.length > 0) { // 存在用户名
            res.json({
                code: 1,
                data: "存在相同的用户名"
            });
            console.log("用户已注册");
        } else { // 添加进入数据库
            var addsql = "INSERT INTO ymatou(username, password, phone) VALUES(?, ?, ?)";
            var addSqlParams = [usr, pwd, phone];
            connection.query(addsql, addSqlParams, function(error, results) {
                console.log(error);
                res.json({
                    code: 2,
                    data: "注册成功"
                })
            })
        }
    });
})

// 登录端接口
app.get('/login', function(req, res) {
    res.status(200);
    // 获取数据
    var usr = req.query.usr;
    var pwd = req.query.pwd;
    // 连接数据库
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'gp12'
    })
    connection.connect();
    // 查询功能
    var sql = `SELECT * FROM ymatou WHERE userName='${usr}'`;
    connection.query(sql, function(error, results, fields) {
        if (results.length > 0) { // 存在用户名
            if (results[0].password == pwd) {
                res.json({
                    code: 3,
                    data: "登录成功"
                })
            } else {
                res.json({
                    code: 4,
                    data: "密码错误"
                })
            }
        } else { // 用户不存在
            res.json({
                code: 5,
                data: "用户名不存在"
            })
        }
    });
})
var server = app.listen(3002, function() {
    var host = server.address().address
    var port = server.address().port
    console.log('listen at http://%s:%s', host, port)
})